package api;

import Utils.DBUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import common.ApplcationVariable;
import lombok.SneakyThrows;
import model.ResultData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/reg")
public class RegServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType(ApplcationVariable.RESPONSE_CONTENT_TYPE);
        int state=200;
        int data=-1;
        String msg="未知错误";
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        if(!StrUtil.isBlank(username) && !StrUtil.isBlank(password)){
            Connection connection = DBUtil.getConnection();
            String sql1="select * from userinfo where username=?";
            PreparedStatement statement1 = connection.prepareStatement(sql1);
            statement1.setString(1,username);
            ResultSet resultSet = statement1.executeQuery();
            if(resultSet.next()){
                msg="您输入的登录名已存在，请更换后再试";
            }else{
                String sql="insert into userinfo(username,password) values(?,?)";
                statement1 = connection.prepareStatement(sql);
                statement1.setString(1,username);
                statement1.setString(2, SecureUtil.md5(password));
                data=statement1.executeUpdate();
                DBUtil.close(null,statement1,connection);
            }
        }else{
            msg="参数错误";
        }
        resp.getWriter().println(JSONUtil.toJsonStr(new ResultData(state,data,msg)));
    }
}
